import { useState, useEffect, useCallback } from "react";
import "./index.less";
import { request } from "../../../common/request";
import { urls } from "../../../common/urls";
import { getMessageUserList } from "../../../util/message";
import { getOtherUser } from '../../../util/getOtherInfo';
import { clearAllMessage, clearMark } from "../../../util/message";
import { getMid } from '../../../util/index';
import store from "../../../store";
import moment from 'moment';

function ChatList(props: any) {
  const { setContent } = props;
  const [active, setActive] = useState(0);
  const [noticeNum, setNoticeNum] = useState(0)
  const [chatList, setChatList] = useState([]);
  const [currentId, setCurrentId] = useState('');

  const getNum = () => {
    request({
      method: "post",
      data: {
        method: urls.noticeNum,
      },
    }).then((res: any) => {
      setNoticeNum(res.data);
    });
  };
  const handleNotice = () => {
    setContent({ type: 'notice' });
  };
  const getList = async () => {
    const res: any = await getMessageUserList();
    const { conversations } = res.data;
    const infos: any = await Promise.all(conversations.map((x: any) => getOtherUser(getMid(x.conversationId), x.conversationType)));
    const list: any = conversations.map((x: any, i: number) => {
      const item = infos[i];
      return {
        ...x,
        ...x.lastMessage,
        ...item,
        username: x.conversationType === 'groupChat' ? item.announcement : item.username,
        avatar: x.conversationType === 'groupChat' ? item.logo : item.avatar,
      }
    });
    if (list.length) {
      setContent({
        type: 'im', id: getMid(list[0].conversationId),
        avatar: list[0].avatar,
        conversationType: list[0].conversationType
      });
      setCurrentId(getMid(list[0].conversationId));
    }
    console.log('-----list', list);
    setChatList(list);
  }

  const handleClear = () => {
    clearAllMessage();
  };

  useEffect(() => {
    getNum();
    setTimeout(() => {
      getList();
    }, 500)
    // 监听state的变化
    const unsubscribe = store.subscribe(() => {
      console.log('监听中..', store.getState())
      getList();
    })
    return () => {
      // 取消监听
      unsubscribe();
    }
  }, [])

  const handleChangeChat = (x: any, i: number) => {
    const { id, avatar, conversationType } = x;
    setContent({ type: 'im', id, avatar, conversationType });
    setActive(i);
    clearMark(id).then((res) => {
      console.log('取消标记监听中..', res)
      getList();
    });
  };
  return (
    <>
      <div className="chat-list">
        {/* title */}
        <div className="chat-list-title title-content">
          <div className="chat-list-title-clear" onClick={handleClear}>
            <div className="chat-list-title-clear-img"></div>
            <p>清空聊天</p>
          </div>
          <div className="chat-list-title-notice" onClick={handleNotice}>
            {noticeNum ? <p className="chat-list-title-notice-num notice-num">{noticeNum}</p> : ''}
          </div>
        </div>
        {/* list */}
        <div className="chat-card-group">
          {chatList.length > 0 && chatList?.map((x: any, i) => {
            return (
              <div
                className="chat-card"
                style={{
                  backgroundColor: `${active === i ? "#E5E5E5" : "transparent"
                    }`,
                }}
                key={x.id}
                onClick={() => handleChangeChat(x, i)}
              >
                <div className="chat-card-left">
                  <img className="avatar" src={x.avatar} alt="" />
                  <div className="chat-card-left-name">
                    <p className="name">{x.comment_name || x.username}</p>
                    <p>{x.msg}</p>
                  </div>
                </div>
                <div className="chat-card-right">
                  <p>{moment(x.time).format('HH:mm')}</p>
                  {x.unReadCount > 0
                    ? <p className="notice-num">{x.unReadCount}</p>
                    : <p className="notice-num-empty"></p>}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

export default ChatList;
